package ni;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * IPGetter is really useful to get local IP and broadcast IP. On windows
 * systems this class is not necessary because the getLocalHost() returns the
 * right result. On ubuntu getLocalHost() returns 127.0.0.1
 *
 * @author gb
 */
public class IpGetter {

    /**
     * Goes through each interface and grabs the first IPv4 address
     *
     * @return the local IPv4 address or null if not found
     * @throws SocketException could be thrown when getting the enumeration of interface
     */
    public static InetAddress getLocalIp() throws SocketException {
        Enumeration<NetworkInterface> enumInterf = NetworkInterface.getNetworkInterfaces();
        InetAddress res = null;
        while (enumInterf.hasMoreElements()) {
            Enumeration<InetAddress> enumIp = enumInterf.nextElement().getInetAddresses();
            while (enumIp.hasMoreElements()) {
                res = enumIp.nextElement();

                if (!res.isLoopbackAddress()) {
                    if (res instanceof Inet4Address) {
                        return res;
                    }
                }
            }
            res = null;
        }

        return res;
    }

    /**
     * Goes through all interfaces and grabs the first IPv4 broadcast address
     *
     * @return the local IPv4 broadcast address or null if not found
     * @throws SocketException could be thrown when getting the enumeration of interface
     */
    public static InetAddress getLocalBroadcastIp() throws SocketException {
        InetAddress broadcast = null;
        Enumeration<NetworkInterface> interfaces
                = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            if (networkInterface.isLoopback()) {
                continue;    // Don't want to broadcast to the loopback interface
            }
            for (InterfaceAddress interfaceAddress
                    : networkInterface.getInterfaceAddresses()) {
                broadcast = interfaceAddress.getBroadcast();
                if (broadcast != null) {
                    if (broadcast instanceof Inet4Address) {
                        return broadcast;
                    }
                }
            }
        }
        return broadcast;
    }
}
